//
//  LoginViewController.m
//  AI
//
//  Created by zjhc on 2018/1/2.
//  Copyright © 2018年 zjhc. All rights reserved.
//

#import "LoginViewController.h"
#import "AuthcodeView.h"
#import "LlbTextField.h"
#import "MainTabBarController.h"
#import "UrlManage.h"
#import "UserManage.h"
#import "UIColor+Extension.h"
#import "AFAppDotNetAPIClient.h"
#import "AIAlertView.h"
#import <SVProgressHUD.h>
@interface LoginViewController ()<UITextFieldDelegate> {
    
    BOOL isLoginFail;

}
- (IBAction)loginAction:(id)sender;
@property (weak, nonatomic) IBOutlet LlbTextField *userName;
@property (weak, nonatomic) IBOutlet LlbTextField *passWord;
@property (weak, nonatomic) IBOutlet LlbTextField *authCode;
@property (weak, nonatomic) IBOutlet UIButton *authCodeView;
- (IBAction)authCodeViewAction:(id)sender;
@property (weak, nonatomic) IBOutlet UIStackView *authCodeStackView;
@property (weak, nonatomic) IBOutlet UIButton *login;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.authCodeStackView .hidden = YES;
    
    self.userName.verticalPadding = 13.5;
    self.userName.horizontalPadding = 75;
    [self setTextFieldLeftImageView:self.userName leftImageName:@"userName" imageLocation:CGRectMake(20, 0, 15, 17)];
    
    self.passWord.secureTextEntry = YES;
    self.passWord.verticalPadding = 13;
    self.passWord.horizontalPadding = 75;
    [self setTextFieldLeftImageView:self.passWord leftImageName:@"passWord" imageLocation:CGRectMake(20, 0, 15, 18)];
    
    self.authCode.verticalPadding = 13.5;
    self.authCode.horizontalPadding = 75;
    [self setTextFieldLeftImageView:self.authCode leftImageName:@"authCode" imageLocation:CGRectMake(20, 0, 15, 17)];
    
    self.userName.layer.borderWidth =  0.1f;
    self.userName.alpha = 0.3;
    self.passWord.alpha = 0.3;
    self.authCode.alpha = 0.3;

    self.passWord.layer.borderWidth = 0.1f;
    self.userName.layer.cornerRadius = 8.0;
    self.passWord.layer.cornerRadius = 8.0;
    self.authCode.layer.cornerRadius = 8.0;
    self.authCodeView.layer.cornerRadius = 8.0;
    self.login.layer.cornerRadius= 8.0;
    
    UILabel *userNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(55, 13, 2, 20)];
     UILabel *passWordLabel = [[UILabel alloc] initWithFrame:CGRectMake(55, 13, 2, 20)];
     UILabel *authCodeLabel = [[UILabel alloc] initWithFrame:CGRectMake(55, 13, 2, 20)];
     userNameLabel.backgroundColor = [UIColor whiteColor];
     passWordLabel.backgroundColor = [UIColor whiteColor];
     authCodeLabel.backgroundColor = [UIColor whiteColor];

    [self.userName addSubview:userNameLabel];
    [self.passWord addSubview:passWordLabel];
    [self.authCode addSubview:authCodeLabel];
    
    //设置placeholder的颜色
    UIColor *placeHolderColor= [UIColor colorWithHexString:@"FFFFFF" alpha:1];
    self.userName.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入用户名" attributes:@{NSForegroundColorAttributeName: placeHolderColor}];
    self.passWord.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入用密码" attributes:@{NSForegroundColorAttributeName: placeHolderColor}];
    self.authCode.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入验证码" attributes:@{NSForegroundColorAttributeName: placeHolderColor}];

    isLoginFail = NO;
    self.userName.delegate = self;
}

-(void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.hidden = YES;
    
    if (isLoginFail) {
        self.authCodeStackView.hidden = NO;
    }
    
    self.tabBarController.tabBar.hidden = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

/**
 *  设置输入框前的图片
 */
- (void)setTextFieldLeftImageView:(UITextField *)textField leftImageName:(NSString *)imageName imageLocation:(CGRect)frame
{
    // 设置左边图片
    UIImageView *leftView  = [[ UIImageView alloc]initWithFrame:frame];
    leftView.image =  [UIImage imageNamed:imageName];
    UIView *uv = [[UIView alloc]initWithFrame:frame];
    [uv addSubview:leftView];
    textField.leftViewMode = UITextFieldViewModeAlways;
    textField.leftView = uv;
//    [self.view bringSubviewToFront:textField.leftView];

}

- (IBAction)loginAction:(id)sender {
//    self.userName.text = @"17681886059";
    ///////////////////////////////////
    //    测试账号
//    self.userName.text =@"18906502080";
//    self.passWord.text = @"123456";
    ///////////////////////////////////
    if (![self mathPhone:self.userName.text]) {
        return;
    }
    
    if (self.passWord.text == nil || [self.passWord.text isEqualToString:@""]) {
//        [HXAlertViewEx showInTitle:@"提示" Message:@"请输入密码" ViewController:self];
        [SVProgressHUD showErrorWithStatus:@"请输入密码"];
        return;
    }
    
    if (isLoginFail) {
        [self getImageAuthCodeService];
    }
    
    [self loginService];

}

- (void)loginService {
    
    //去掉空格操作
    NSString *userNameString = [self.userName.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSString *passWordString = self.passWord.text;

    NSString *uid=[ContextUtil identifierForVendor];
    if (uid.length > 32) {
        uid = [uid substringToIndex:32];
    }else if(uid.length < 32){
        int num = 10;
        for (int i = 1; i <= 32 - uid.length; i ++) {
            num = num * i;
        }
        uid = [NSString stringWithFormat:@"%@%lu",uid,10^(32-uid.length - 1)];
    }
    [[UserManage sharedUserManage] setUid:uid];

    
    [AFAppDotNetAPIClient postAsynchronous:[UrlManage sharedManager].login parameter:@{@"telphone":userNameString,@"password":passWordString,@"uid":uid} successBlock:^(NSDictionary *result, NSError *error) {

        if ([[result objectForKey:@"code"] isEqualToString:@"0"]) {
            NSDictionary * dict = [result objectForKey:@"data"];

            [UserManage sharedUserManage].userNmae = userNameString;
//            [UserManage sharedUserManage].password = @"123456";

            [NSUserDefaultsUtil setToken:[dict objectForKey:@"access_token"]];
            [NSUserDefaultsUtil setUserPhone:userNameString];
            UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            MainTabBarController *home =(MainTabBarController *)[mainStoryboard instantiateViewControllerWithIdentifier:@"MainTabBarController"];
            [UIApplication sharedApplication].delegate.window.rootViewController = home;
        } else {
            [SVProgressHUD showErrorWithStatus:[result objectForKey:@"msg"]];
            isLoginFail = YES;
            self.authCodeStackView .hidden = NO;
            [self getAuthCode];
        }
    } errorBlock:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:error.userInfo.description];
    }];
}

#pragma mark -- getImageAuthCodeService
- (void)getImageAuthCodeService {
//    NSDictionary *params = @{@"code":self.authCode.text,@"phototoken":self.authCodeView.token};
//    [HXHttpUtils requestJsonLoginWithUrlStr:@"/userservice/validphotocode" params:params andRequestType:WFRequestTypeLogin onComplete:^(NSError *error, NSDictionary *resultJson) {
//        if (!error) {
//            [self getLonginHttp];
//        }else{
//            WTAlterView *tipView = [[WTAlterView alloc]initAlterWithMessage:@"图形验证码" andAlterY:ViewFrame_Y(self.loginView)];
//            [tipView show];
//        }
//    }];
}


-(BOOL)mathPhone:(NSString *)phone{
    if (!phone || [phone isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"请输入手机号"];
        return NO;
    }
    if (![HXNSStringUtil isMobilePhoneNumber:phone]) {
        [SVProgressHUD showErrorWithStatus:@"手机号格式不正确,请重新输入"];
        return NO;
    }
    return YES;
}

#pragma mark -获取验证码
- (void) getAuthCode {
    
    if ([UserManage sharedUserManage].uid == nil) {
        NSString *uid=[ContextUtil identifierForVendor];
        if (uid.length > 32) {
            uid = [uid substringToIndex:32];
        }else if(uid.length < 32){
            int num = 10;
            for (int i = 1; i <= 32 - uid.length; i ++) {
                num = num * i;
            }
            uid = [NSString stringWithFormat:@"%@%lu",uid,10^(32-uid.length - 1)];
        }
        [[UserManage sharedUserManage] setUid:uid];
    }
    
       NSDictionary *params = @{@"uid":[UserManage sharedUserManage].uid};

    [WTHttpRequest requestAuthCodeGetWithUrlStr:[UrlManage sharedManager].authCode params:params onComplete:^(NSError *error, NSDictionary *resultJson) {
        if (!error) {
       [self.authCodeView setBackgroundImage:[resultJson objectForKey:@"image"] forState:UIControlStateNormal];
        }else{
            [SVProgressHUD showErrorWithStatus:error.domain];
        }
    }];
}
- (UIImage *)decodeBase64ToImage:(NSString *)strEncodeData {
    NSData *data = [[NSData alloc]initWithBase64EncodedString:strEncodeData options:NSDataBase64DecodingIgnoreUnknownCharacters];
    return [UIImage imageWithData:data];
}

- (IBAction)authCodeViewAction:(id)sender {
    [self getAuthCode];
}

#pragma mark - 通用提醒弹窗
- (void)alertMessage:(NSString *)message {
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                   message:message
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel  handler:^(UIAlertAction * action) {
    }];
    
    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - 限制文本输入的监听函数
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == self.userName) {
        //这里的if时候为了获取删除操作,如果没有次if会造成当达到字数限制后删除键也不能使用的后果.
        if (range.length  == 1 && string.length == 0) {
            return YES;
        } else if (self.userName.text.length >=11){
            self.userName.text = [self.userName.text substringToIndex:11];
            return NO;
        }
    }
    return YES;
}


@end
